﻿using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
using UnityEditor;
using LitJson;
public class LoadScene: MonoBehaviour
{

    [MenuItem("GameObject/ImprotXML")]
    public static void LoadSenceXML()
    {

        //电脑和iphong上的路径是不一样的，这里用标签判断一下。
#if UNITY_EDITOR
        string filepath = Application.dataPath + "/StreamingAssets" + "/my.xml";
#elif UNITY_IPHONE
	  string filepath = Application.dataPath +"/Raw"+"/my.xml";
#endif
        //如果文件存在话开始解析。
        if (File.Exists(filepath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("gameObjects").ChildNodes;
            foreach (XmlElement scene in nodeList)
            {
                //因为我的XML是把所有游戏对象全部导出， 所以这里判断一下只解析需要的场景中的游戏对象
                //JSON和它的原理类似
                string path = scene.GetAttribute("name");
                string name = path.Substring(path.LastIndexOf('/')+1,path.LastIndexOf('.')-path.LastIndexOf('/')-1);
                Debug.Log(name);
                if (!name.Equals(Application.loadedLevelName))
                {
                    continue;
                }

                foreach (XmlElement gameObjects in scene.ChildNodes)
                {

                    string asset = "Assets/Prefab/" + gameObjects.GetAttribute("asset");
                    Vector3 pos = Vector3.zero;
                    Vector3 rot = Vector3.zero;
                    Vector3 sca = Vector3.zero;
                    foreach (XmlElement transform in gameObjects.ChildNodes)
                    {
                        foreach (XmlElement prs in transform.ChildNodes)
                        {
                            if (prs.Name == "position")
                            {
                                foreach (XmlElement position in prs.ChildNodes)
                                {
                                    switch (position.Name)
                                    {
                                        case "x":
                                            pos.x = float.Parse(position.InnerText);
                                            break;
                                        case "y":
                                            pos.y = float.Parse(position.InnerText);
                                            break;
                                        case "z":
                                            pos.z = float.Parse(position.InnerText);
                                            break;
                                    }
                                }
                            }
                            else if (prs.Name == "rotation")
                            {
                                foreach (XmlElement rotation in prs.ChildNodes)
                                {
                                    switch (rotation.Name)
                                    {
                                        case "x":
                                            rot.x = float.Parse(rotation.InnerText);
                                            break;
                                        case "y":
                                            rot.y = float.Parse(rotation.InnerText);
                                            break;
                                        case "z":
                                            rot.z = float.Parse(rotation.InnerText);
                                            break;
                                    }
                                }
                            }
                            else if (prs.Name == "scale")
                            {
                                foreach (XmlElement scale in prs.ChildNodes)
                                {
                                    switch (scale.Name)
                                    {
                                        case "x":
                                            sca.x = float.Parse(scale.InnerText);
                                            break;
                                        case "y":
                                            sca.y = float.Parse(scale.InnerText);
                                            break;
                                        case "z":
                                            sca.z = float.Parse(scale.InnerText);
                                            break;
                                    }
                                }
                            }
                        }

                        //拿到 旋转 缩放 平移 以后克隆新游戏对象
                        Debug.Log(asset);
                        Object obj = UnityEditor.AssetDatabase.LoadAssetAtPath(asset, typeof(GameObject));
                        GameObject ob = (GameObject)Instantiate(obj, pos, Quaternion.Euler(rot));
                        ob.transform.localScale = sca;
                        ob.name = obj.name;
                    }
                }
            }
        }
    }

    [MenuItem("GameObject/ImprotJSON")]
    public static void LoadSenceJSON()
    {
#if UNITY_EDITOR
        string filepath = Application.dataPath + "/StreamingAssets" + "/json.txt";
#elif UNITY_IPHONE
	  string filepath = Application.dataPath +"/Raw"+"/json.txt";
#endif

        StreamReader sr = File.OpenText(filepath);
        string strLine = sr.ReadToEnd();
        JsonData jd = JsonMapper.ToObject(strLine);
        JsonData gameObjectArray = jd["GameObjects"];
        int i, j, k;
        for (i = 0; i < gameObjectArray.Count; i++)
        {
            JsonData senseArray = gameObjectArray[i]["scenes"];
            for (j = 0; j < senseArray.Count; j++)
            {
                string path = (string)senseArray[j]["name"];
                string name = path.Substring(path.LastIndexOf('/') + 1, path.LastIndexOf('.') - path.LastIndexOf('/') - 1);


                if (!name.Equals(Application.loadedLevelName))
                {
                    continue;
                }
                JsonData gameObjects = senseArray[j]["gameObject"];

                for (k = 0; k < gameObjects.Count; k++)
                {
                    string asset = "Assets/Prefab/" + (string)gameObjects[k]["asset"];
                    Vector3 pos = Vector3.zero;
                    Vector3 rot = Vector3.zero;
                    Vector3 sca = Vector3.zero;

                    JsonData position = gameObjects[k]["position"];
                    JsonData rotation = gameObjects[k]["rotation"];
                    JsonData scale = gameObjects[k]["scale"];

                    pos.x = float.Parse((string)position["x"]);
                    pos.y = float.Parse((string)position["y"]);
                    pos.z = float.Parse((string)position["z"]);

                    rot.x = float.Parse((string)rotation["x"]);
                    rot.y = float.Parse((string)rotation["y"]);
                    rot.z = float.Parse((string)rotation["z"]);

                    sca.x = float.Parse((string)scale["x"]);
                    sca.y = float.Parse((string)scale["y"]);
                    sca.z = float.Parse((string)scale["z"]);

                    Debug.Log(asset);
                    Object obj = UnityEditor.AssetDatabase.LoadAssetAtPath(asset, typeof(GameObject));
                    GameObject ob = (GameObject)Instantiate(obj, pos, Quaternion.Euler(rot));
                    ob.transform.localScale = sca;
                    ob.name = obj.name;

                }

            }
        }

    }
}